package com.xxd.spring.boot.demo.hubajun.uti;

import com.xxd.spring.boot.demo.hubajun.entity.StudentEntity;

import java.sql.*;
import java.util.Objects;


public class JDBC {
    private static Connection init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            return DriverManager.getConnection(
                    "jdbc:mysql://127.0.0.1:3306/test_ku?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC",
                    "root",
                    "123456h");
        } catch (SQLException | ClassNotFoundException throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public static void select() {
        try {
            ResultSet resultSet = Objects.requireNonNull(init())
                    .createStatement(
                            ResultSet.TYPE_SCROLL_INSENSITIVE,
                            ResultSet.CONCUR_UPDATABLE)
                    .executeQuery("select * from user");
            //insert
            resultSet.moveToInsertRow();
            resultSet.updateInt("num", 1);
            resultSet.updateString("name","xxx");
            resultSet.insertRow();

            resultSet.moveToInsertRow();
            resultSet.updateInt("num", 2);
            resultSet.updateString("name","yyy");
            resultSet.insertRow();
            //update
            resultSet.moveToCurrentRow();
            resultSet.absolute(1);
            resultSet.updateString("name", "zzz");
            resultSet.updateRow();
            System.out.println(resultSet);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    public static void insert(StudentEntity studentEntity) {
        try {
            String sql = "INSERT INTO stumanager.user(num,name,sex,address)VALUES('" +
                    studentEntity.getNum() + "','" +
                    studentEntity.getName() + "','" +
                    studentEntity.getSex() + "','" +
                    studentEntity.getAddress() + "')";
            int n = Objects.requireNonNull(init()).createStatement().executeUpdate(sql);
            if (n > 0) {
                System.out.println("添加成功" + n);
            } else {
                System.out.println("添加失败" + n);
            }
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }
}
